package jwt

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"strings"
)

const (
	PREFIX = "Bearer "
	SECRET = "abcdefghijklmnopqrstuvwxyz"
)

type CustomizeClaims struct {
	UserKey  string `json:"user_key"`
	SysKey   string `json:"sys_key"`
	UserID   int64  `json:"user_id"`
	Username string `json:"username"`
	jwt.RegisteredClaims
}

func replaceTokenPrefix(tokenStr string) string {
	if strings.HasPrefix(tokenStr, PREFIX) {
		return tokenStr[len(PREFIX):]
	}
	return tokenStr
}

func ParseJWT(tokenStr string) (*CustomizeClaims, error) {
	tokenStr = replaceTokenPrefix(tokenStr)
	customizeClaims := &CustomizeClaims{}
	_, err := jwt.ParseWithClaims(tokenStr, customizeClaims, func(token *jwt.Token) (any, error) {
		// 验证算法
		if token.Method != jwt.SigningMethodHS512 {
			return nil, fmt.Errorf("签名算法错误，期望HS512，实际: %v", token.Header["alg"])
		}
		return []byte(SECRET), nil
	})
	if err != nil {
		return nil, fmt.Errorf("解析JWT失败: %w", err)
	}
	return customizeClaims, nil
}
